package com.sp.system.user.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sp.system.user.core.entity.Menu;
import com.sp.system.user.customer.mapper.MenuMapper;
import com.sp.system.user.customer.service.IMenuService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Override
    public List<Menu> queryMenuList(Menu menuQuery) {
        QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>(menuQuery);

        List<Menu> menuList = baseMapper.selectList(menuQueryWrapper);

        Map<String , Menu> map = new HashMap<>();
        if(menuList != null && menuList.size() > 0){
            map = menuList.stream().collect(Collectors.toMap(Menu::getId, Menu -> Menu,(oldValue, newValue) -> oldValue));
        }
        List<String> listRemove = new ArrayList<>();

        for ( Map.Entry<String, Menu> entry : map.entrySet() ) {
            Menu menu = entry.getValue();
            String sParentId = menu.getParentId();
            Menu menuTree = map.get(sParentId);
            if ( menuTree != null ) {
                if(menuTree.getChildren() == null){
                    menuTree.setChildren(new ArrayList<Menu>());
                }
                menuTree.getChildren().add(menu);
                listRemove.add(entry.getKey());
            }
        }
        List<Menu> menus = new ArrayList<Menu>();
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next().toString();
            if(!listRemove.contains(key)){
                menus.add(map.get(key));
            }
        }
        return  menus;
    }

}
